package com.cac.demo.newCode.sorting.service.Impl;

import com.cac.demo.newCode.sorting.dto.LocalLogDTO;
import com.cac.demo.newCode.sorting.service.LocalLogService;
import com.cac.demo.newCode.sorting.utils.LocalLogUtil;
import com.cac.demo.util.adapter.ResponseMsg;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Service
public class LocalLogServiceImpl implements LocalLogService {

    @Resource
    private LocalLogUtil localLogUtil;

    @Override
    public ResponseMsg<Object> getLogPage(LocalLogDTO localLogDTO) {
        String sql = "SELECT\n" +
                "  id,\n" +
                "  level,\n" +
                "  logger_name,\n" +
                "  message,\n" +
                "  exception,\n" +
                "  create_time,\n" +
                "  method,\n" +
                "  ip_address,\n" +
                "  request_param,\n" +
                "  response_param \n" +
                "FROM\n" +
                "  local_log  where 1=1 ";
        if (localLogDTO.getMethod() != null && localLogDTO.getMethod() != "") {
            sql += "and method = " + localLogDTO.getMethod() + "";
        }
        if (localLogDTO.getCreateStartDate() != null && localLogDTO.getCreateStartDate() != "" && localLogDTO.getCreateEndDate() != null && localLogDTO.getCreateEndDate() != "") {
            sql += "AND create_time BETWEEN '" + localLogDTO.getCreateStartDate() + "'"+" AND '" +  localLogDTO.getCreateEndDate() + "'";

        }

        sql += " LIMIT " + localLogDTO.getSize() + " OFFSET (" + localLogDTO.getCurrent() + " - 1) * " + localLogDTO.getSize();
        List<LocalLogDTO> localLogDTOS = localLogUtil.executeSqlQuery(sql);
        String sql1 = " SELECT COUNT(1) AS pageTotal FROM local_log where 1=1";
        if (localLogDTO.getMethod() != null && localLogDTO.getMethod() != "") {
            sql1 += "and method = " + localLogDTO.getMethod() + "";
        }
        if (localLogDTO.getCreateStartDate() != null && localLogDTO.getCreateStartDate() != "" && localLogDTO.getCreateEndDate() != null && localLogDTO.getCreateEndDate() != "") {
            sql1 += " AND create_time BETWEEN '" + localLogDTO.getCreateStartDate() + "'"+" AND '" +  localLogDTO.getCreateEndDate() + "'";

        }
        String pageTotal = localLogUtil.executeSqlCount(sql1);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("pageTotal",pageTotal);
        map.put("size",localLogDTO.getSize());
        map.put("current",localLogDTO.getCurrent());
        map.put("data",localLogDTOS);
        return new ResponseMsg<>().setResponseBody(map);
    }
}
